#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <vector>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <functional>
#include <semaphore.h>
#include <jsoncpp/json/json.h>
#include <sys/select.h>
#include <signal.h>
#include <unordered_set>
#include <queue>
#include "TcpServer.hpp"
#include "Protocol.hpp"
#include "Task.hpp"
#define PORT 8081
using namespace std;
#define MAXNUM 10
class HttpServer
{
public:
    HttpServer(int port = PORT, int maxnum = MAXNUM)
        : _port(port), _maxnum(maxnum), num(1), tid(_maxnum)
    {
        _increase = {false, -1};
    }
    void InitServer()
    {
        // 对信号SIGPIPE进行忽略，如果不忽略在写入时候可能直接崩溃server
        signal(SIGPIPE, SIG_IGN);
        tcpserver = TcpServer::getserver(_port);
        _listensock = tcpserver->Sock();
    }
    static void *Accepter(void *args)
    {
        HttpServer *hp = (HttpServer *)args;
        while (1)
        {
            int sock = accept(hp->_listensock, nullptr, nullptr);
            if (hp->_socks.find(sock) == hp->_socks.end() && hp->num < hp->_maxnum&&sock!=-1)
            {
                hp->_socks.insert(sock);
                hp->_increase = {true, sock};
                hp->sock=sock;
            }
            else
                cout << "链接失败" << endl;
        }
        return nullptr;
    }
    static void *Recver(void *args)
    {
    HttpServer *hp = (HttpServer *)args;
    int sock=hp->sock;
        while (1)
        {
            char buffer[1024];
            memset(buffer, 0, sizeof buffer);
            int n = recv(sock, &buffer, sizeof buffer, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                string message = buffer;
                Task task(sock, message);
                task.ProcessOn();
            }
            sleep(1);
        }
        return nullptr;
    }
    void Loop()
    {
        pthread_create(&tid[0], nullptr, Accepter, (void *)this);
        while (!stop)
        {
            if(_increase.first&&_increase.second!=-1&&num<_maxnum)
            {
                pthread_create(&tid[num++],nullptr,Recver,(void*)this);
                _increase={false,-1};
            }
        }
    }

private:
    TcpServer *tcpserver;
    bool stop = false;
    int _listensock;
    int _port;
    int _maxnum = MAXNUM;
    int num;
    int sock=0;  
    unordered_set<int> _socks;
    vector<pthread_t> tid;
    pair<bool, int> _increase;
};
